"""
性别检测模块
使用腾讯云人脸识别服务进行性别检测
"""

# 腾讯云密钥配置
TENCENT_CLOUD_SECRET_ID = "AKIDLfswsoBGG4e1CAuRnxxlLm3HKDtMbw8A"
TENCENT_CLOUD_SECRET_KEY = "ylMkvvjP7oIbigeWFuOficLrDSwUr57w"
TENCENT_CLOUD_REGION = "ap-beijing"
# 尝试导入腾讯云SDK相关库
TENCENT_SDK_AVAILABLE = False

# 全局变量用于存储GUI回调函数
gui_log_callback = None

def set_gui_log_callback(callback):
    """设置GUI日志回调函数"""
    global gui_log_callback
    gui_log_callback = callback

def detect_gender_from_image_api(image_data, secret_id="", secret_key="", region="ap-beijing"):
    """
    使用腾讯云人脸识别API检测图像中的性别
    
    参数:
        image_data: 图像文件路径或图像字节数据
        secret_id: 腾讯云SecretId（可选，如果不提供则使用默认值）
        secret_key: 腾讯云SecretKey（可选，如果不提供则使用默认值）
        region: 腾讯云区域（可选，默认为ap-beijing）
        
    返回:
        dict: 包含gender和confidence的字典，如果失败则返回None
    """
    global gui_log_callback
    
    # 检查模块是否可用
    if not MODULE_AVAILABLE:
        error_msg = "腾讯云人脸识别模块不可用，请检查依赖库是否正确安装"
        if gui_log_callback:
            gui_log_callback(error_msg + "\n")
        else:
            print(error_msg)
        return None
    
    # 检查是否提供了有效的密钥
    if not secret_id or not secret_key:
        # 使用默认密钥（注意：实际使用时应通过参数传入或环境变量设置）
        secret_id = TENCENT_CLOUD_SECRET_ID
        secret_key = TENCENT_CLOUD_SECRET_KEY
        
        # 如果默认密钥也为空，则提示用户配置
        if not secret_id or not secret_key:
            error_msg = "未提供腾讯云API密钥，请在调用时传入有效的SecretId和SecretKey"
            if gui_log_callback:
                gui_log_callback(error_msg + "\n")
            else:
                print(error_msg)
            return None
    
    tmp_filename = None
    try:
        # 记录开始处理日志
        log_msg = "开始调用腾讯云人脸识别API进行性别检测\n"
        if gui_log_callback:
            gui_log_callback(log_msg)
        else:
            logging.info(log_msg)
        
        # 处理图像数据
        if isinstance(image_data, str):
            # 如果是文件路径，读取文件内容
            with open(image_data, 'rb') as f:
                image_bytes = f.read()
        else:
            # 如果是字节数据，直接使用
            image_bytes = image_data

        # 将图像数据转换为base64编码
        image_base64 = base64.b64encode(image_bytes).decode('utf-8')

        # 初始化腾讯云认证信息
        cred = credential.Credential(secret_id, secret_key)
        
        # 配置HTTP profile
        httpProfile = HttpProfile()
        httpProfile.endpoint = "iai.tencentcloudapi.com"
        httpProfile.reqMethod = "POST"
        httpProfile.reqTimeout = 30

        # 实例化客户端profile
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 使用最新的签名方法
        
        # 实例化人脸识别客户端
        client = iai_client.IaiClient(cred, region, clientProfile)

        # 构造请求
        req = models.DetectFaceRequest()
        params = {
            "Image": image_base64,
            "NeedFaceAttributes": 1,  # 需要人脸属性信息
            "FaceModelVersion": "3.0",  # 使用最新的人脸识别模型
            "MinFaceSize" : 10,
        }
        req.from_json_string(json.dumps(params))

        # 发送请求并获取结果
        resp = client.DetectFace(req)
        
        # 解析结果
        if resp.FaceInfos and len(resp.FaceInfos) > 0:
            # 取第一个人脸的结果
            face_info = resp.FaceInfos[0]
            gender = face_info.FaceAttributesInfo.Gender
            # 腾讯云返回的性别值: 男性为1，女性为-1
            gender_str = "Male" if gender > 0 else "Female"
            # 使用偏移值作为置信度的近似值，转换为百分比
            confidence = min(100, abs(gender) * 100)
            
            success_msg = f"性别检测成功: {gender_str} (置信度: {confidence:.1f}%)\n"
            if gui_log_callback:
                gui_log_callback(success_msg)
            else:
                logging.info(success_msg)
            
            return {
                'gender': gender_str,
                'confidence': confidence
            }
        else:
            warning_msg = "未检测到人脸\n"
            if gui_log_callback:
                gui_log_callback(warning_msg)
            else:
                logging.warning(warning_msg)
            return None
            
    except TencentCloudSDKException as e:
        error_msg = f"腾讯云API调用失败: {e}\n"
        if gui_log_callback:
            gui_log_callback(error_msg)
        else:
            logging.error(error_msg)
        return None
    except Exception as e:
        error_msg = f"处理图像数据时发生错误: {e}\n"
        if gui_log_callback:
            gui_log_callback(error_msg)
        else:
            logging.error(error_msg)
        return None
    finally:
        # 清理临时文件（如果有的话）
        if isinstance(image_data, (bytes, bytearray)) and tmp_filename and os.path.exists(tmp_filename):
            os.unlink(tmp_filename)

MODULE_AVAILABLE = False

try:
    # 动态导入腾讯云SDK相关模块
    from tencentcloud.common import credential
    from tencentcloud.common.profile.client_profile import ClientProfile
    from tencentcloud.common.profile.http_profile import HttpProfile
    from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
    from tencentcloud.iai.v20180301 import iai_client, models
    
    import logging
    import base64
    import os
    import tempfile
    import json

    TENCENT_SDK_AVAILABLE = True

    # 标记模块导入成功
    MODULE_AVAILABLE = True

except ImportError as e:
    # 模块导入失败时的处理
    TENCENT_SDK_AVAILABLE = False
    
    logging = None
    try:
        import logging
    except ImportError:
        import traceback
        print("无法导入logging模块")
        logging = type('Logger', (), {
            'error': lambda x, *args: print(f"ERROR: {x % args}" if args else f"ERROR: {x}"),
            'warning': lambda x, *args: print(f"WARNING: {x % args}" if args else f"WARNING: {x}"),
            'info': lambda x, *args: print(f"INFO: {x % args}" if args else f"INFO: {x}"),
        })()
    
    logging.warning(f"腾讯云人脸识别模块导入失败: {e}")
    logging.warning("性别检测功能将不可用")
    
    MODULE_AVAILABLE = False
except Exception as e:
    # 其他异常处理
    TENCENT_SDK_AVAILABLE = False
    
    logging = None
    try:
        import logging
    except ImportError:
        import traceback
        print("无法导入logging模块")
        logging = type('Logger', (), {
            'error': lambda x, *args: print(f"ERROR: {x % args}" if args else f"ERROR: {x}"),
            'warning': lambda x, *args: print(f"WARNING: {x % args}" if args else f"WARNING: {x}"),
            'info': lambda x, *args: print(f"INFO: {x % args}" if args else f"INFO: {x}"),
        })()
    
    logging.error(f"腾讯云人脸识别模块初始化失败: {e}")
    
    MODULE_AVAILABLE = False